<?php
/**
 * 商户商品控制器
 * @version 1.0
 * @author ezhu <ezhu@jipukeji.com>
 */

namespace Shop\Controller;

use Admin\Controller\DatabaseController;
use myclass\Sku;
class ItemController extends CommonController {
    
    protected function _initialize(){
        parent::_initialize();
        // 左侧导航
        $this->assign('sign','item');
    }

    // 区域价格 删除
    public function position_del(){
        if(IS_AJAX){
            $id = I('id');
            $send = array(
                1 => array('message' => '删除成功' , 'status' => true ),
                2 => array('message' => '删除失败' , 'status' => false ),
            );
            // 检查是否能删除，后续补上
            $code = M("Zone_price")->where('id ='.$id.' and store_id='.$this->store_id )->delete() ? 1 : 2; 
            $this->ajaxReturn($send[$code]);
        }
    }

    //商品区域价格配置
    public function position(){
        if(IS_POST){
            if (!check_form_hash()) $this->error('请不要重复提交');
            $areas = I('areas' ,'');
            $id    = I('id' ,'');
            // 删除被移除的数据
            if($orig_id = M('Zone_price')->where('store_id ='.$this->store_id)->getField('id' ,true)){
                $diff = empty($id) ? $orig_id : array_diff($orig_id  ,$id );
                if($diff){
                    $map['id'] = array( 'in', implode(',' , $diff));
                    $map['store_id'] = $this->store_id;
                    M('Zone_price')->where($map)->delete();
                    $pass = true;
                }
            }
            if(empty($areas)){
                if($pass){
                    $this->success('操作成功', U('position'));
                }else{
                    $this->error('请完善你要填的内容', U('position'));
                }
            }
            $areas = array_filter($areas);
            foreach($areas as $k => $v){
                $temp = explode('|||' , $v );
                $data[$k] = array(
                    'store_id'      => $this->store_id,
                    'zone_name'     => $_POST['kd'][$k]['zone'],
                    'areas_name'    => $temp[1],
                    'areas'         => $temp[0],
                    'mtime'         => time(),
                    'rate'          => $_POST['kd'][$k]['zone_rate'],
                );
                $data[$k]['id'] = $id[$k];
                if(!empty($data[$k]['id'])){ 
                    M('Zone_price')->save($data[$k]);
                    unset($data[$k]);
                    $res = true;
                }else{
                    $data[$k] = array_filter($data[$k]);
                }
            }
            $data = array_filter($data);
            sort($data);
            if($data){
                $res = M('Zone_price')->addAll($data) ;
            }
            $res ? $this->success('操作成功') : $this->error('操作失败,请稍后再试');
        }
        if($info  = M('Zone_price')->where('store_id ='.$this->store_id)->order('id asc')->select()){
            //店铺修改后销售区域
            $data = M('Zone_used')->where('store_id='.$this->store_id)->getField('areas');
            $t_zone = explode(',',$data);
            foreach ($info as $k => $v) {
               $zone = explode(',',$v['areas']);
               $jiao = array_intersect($t_zone,$zone);
               if (implode(',',$zone) == implode(',',$jiao)) {
                   $info[$k]['is_exist'] = 1;
               }else{
                   $info[$k]['is_exist'] = 0;
               }
            }
            $this->assign('data' , $info);
        }
        if(!M('ZoneUsed')->where('store_id ='.$this->store_id)->getField('areas')){
            $this->error('请先设置可售区域' , U('available_zone'));
        }
        $this->meta_title = '独立指定地区';
        $this->display();
    }
    
    /**
     * 商品列表
     * @author ezhu <ezhu@jipukeji.com>
     */
    public function index() {

        $status = I('get.status');
        $keywords = I('get.keywords');
        $cid_1 = I('get.cid_1');
        $cid_2 = I('get.cid_2');
        $cid_3 = I('get.cid_3');
        $uid = $_SESSION['jipushop_home']['user_auth']['uid']?$_SESSION['jipushop_home']['user_auth']['uid']:0;
        $user = D('Addons://StoreSel/StoreSel')->where(array('member_id' => $uid))->find();

        $_order = (I('request._order') == 'desc') ? 'asc' : 'desc';
        $this->cid_1 = D('itemCategory')->getTree(0,'id,pid,name' , $this->store_id);
        $where['store_id'] = $this->store_id;
        $storage_alarm  = D('store')->where(array('store_id' => $this->store_id))->getField('storage_alarm');

        // 搜索条件
        if($cid_1){
            if(!$cid_2){
                $cate_ids = M('StoreClass')->where('pid ='.$cid_1)->getField('id' ,true);
                $cate_ids = array_merge((array)$cate_ids ,(array)$cid_1 );
                $where['store_cid'] = array('in' ,$cate_ids); 
            }else{
                $where['store_cid'] = $cid_1;  
            }
            $this->cid_2 = D('itemCategory')->getTree($cid_1,'id,pid,name',$this->store_id);
        }
        if($cid_2 && !empty($cid_1)){
            if(M('StoreClass')->where('id ='.$cid_2.' and pid ='.$cid_1)->getField('id' ,true)){
                $where['store_cid'] = $cid_2;
            }
        }
      
        if(in_array($status,array('0','1','-2'))){
            $where['status'] = $status;
        }else{
            $where['status'] = array('in', '0,1,-2');
        }
        if(!empty($keywords)){
            $where['_string'] = ' (`name` like "%'.$keywords.'%") OR (`number` like "%'.$keywords.'")';
        }
        if($_GET['store']){
            $where['stock'] = array('elt',$storage_alarm);
        }
        // 获取商品列表
        $list = $this->lists(M('Item'), $where);
        if($list){
            foreach($list as &$v){
                $v['category'] = '';
                //分类处理
                if($v['cid_1']){
                    $v['category'] = M('item_category')->where(array('id'=>$v['cid_1']))->getField('name');
                }
                if($v['cid_2']){
                    $v['category'] .= '/'. M('item_category')->where(array('id'=>$v['cid_2']))->getField('name');
                }
                if($v['cid_3']){
                    $v['category'] .= '/'. M('item_category')->where(array('id'=>$v['cid_3']))->getField('name');
                }
            }
        }
    
        int_to_string($list, $map = array(
            'status' => array(0 => '上架', -1 => '删除',1 => '下架', 2 => '草稿' , -2 => '已违规下架')
        ));
    
        //记录当前列表页的Cookie
        Cookie('__forward__',$_SERVER['REQUEST_URI']);
    
        //模板输出变量赋值
        $this->assign('_order', $_order);
        $this->assign('list', $list);
        $this->assign('status', $status);
        $this->assign('user', $user);
        $this->meta_title = '商品列表';
        $this->display();
    }
    
    
    /**
     * 商品添加
     */
    function add(){
        // 判断当前商户是否还可以上传商品 BUDDHA 20170328 start
        $grade_id = M('Store')->where(array('store_id'=>$_SESSION['jipushop_store']['seller_user']['store_id']))->getField('grade_id');
        $_data = M('StoreGrade')->find($grade_id);
        $_count = M('Item')->where(array('store_id'=>$_SESSION['jipushop_store']['seller_user']['store_id'],'status'=>1))->count();
        if ($_data['goods_limit'] <= $_count) {
            $this->error('上传商品数目超过店铺等级限制数目，请联系平台管理员');
        }
        $_imageIDs = M('Item')->where(array('store_id'=>$_SESSION['jipushop_store']['seller_user']['store_id'],'status'=>1))->getField('id,images');
        $_imageIDs = array_values($_imageIDs);
        $_ids = '';
        if (!empty($_imageIDs)) {
            foreach ($_imageIDs as $key => $value) {
                $_ids = $value;
                if ($key > 0) {
                    $_ids .= ','. $value;
                }    
            }
            $_num = count(explode(',',$_ids));
            if ($_data['album_limit'] <= $_count) {
                $this->error('上传商品图片超过店铺等级限制数目，请联系平台管理员');
            }
        }
        // 判断当前商户是否还可以上传商品 BUDDHA 20170328 end

        // 区域价格 确定是否开启后便进行检查
        if(C("START_POSITION") && !M('ZoneUsed')->where('store_id ='.$this->store_id)->getField('id')){
            $this->error( '请联系网站管理员设置可售区域');
        }
    	if(C("START_POSITION")){
    	  $zoneinfo = M('ZonePrice')->where('store_id ='.$this->store_id)->field('id,rate')->select();
    	  $this->zoneinfo  = json_encode($zoneinfo);
    	}
        $data = array();
        $data['cid_1'] = I('cid_1');
        $data['cid_2'] = I('cid_2');
        $data['cid_3'] = I('cid_3');
        // 获取select 下拉数据列表
        $option['name'] = 'store_cid';
        $selMap['pid'] = 0;
        $selMap['status'] = 1;
        $selMap['store_id'] = $this->store_id;
        $select_html = getSelect('StoreClass',$option,$selMap);
        // 运费模板
        $transport = M('Transport')->where(array('store_id'=>$this->store_id))->select();
        //获取店铺品牌
        $brand = M('Brand')->order("sort")->select();//->where(array('store_id'=>$this->store_id))
        $this->assign('brand',$brand);
        $this->assign('transport',$transport);
        $this->assign('select_html', $select_html);
        $this->assign('data', $data);
        $this->meta_title = '新增商品';
        $this->display('edit');
    }
    
    
    /**
     * 编辑商品 --yzs
     */
    public function edit(){
        $data = array();
        $id = I('get.id', '');
        $model = D('Item');
        if(IS_POST){
            if($model->create()){
                // 运费类型计算
                $transport_type = I('transport_type');
                if($transport_type == 1){ //固定运费
                    $model->transport_id = 0;
                }else{
                    $model->freight = 0;
                }

                if($_POST['id']){
                    $type = '编辑';
                    $rst = $config->save();
                }else{
                    $type = '添加';
                    $rst = $config->add();
                }
                if($rst !== false){
                    $this->success($type.'成功,现跳转到修改！',U('Shop/Item/edit/id/482.html')); //Shop/Item/index  Shop/Item/edit/id/482.html
                }else{
                    $this->error($type.'失败');
                }
            }else{
                $this->error($model->getError());
            }
            exit;
        }
        
        if(!empty($id)){
            /*获取一条记录的详细数据*/
            $Item = D('Item');
            $sku=new Sku();
            $sku->shoptype("shante");
            $sku->updateItemCategoryFromMapShante($id);
            $data = $Item->detail($id);
            //检查传递的商品ID 是否是此店铺的
            if(!$data){
                $this->error('无效的商品ID！');
            }
            if ($data['store_id'] != $this->store_id) {
                $this->error('你没有修改此商品权限！');
            }
            $title = '编辑商品';
        }else{
            $title = '添加商品';
        }
        // 获取select 下拉数据列表
        $option['name'] = 'store_cid';
        $selMap['pid'] = 0;
        $selMap['status'] = 1;
        $selMap['store_id'] = $this->store_id;
        $select_html = getSelect('StoreClass',$option,$selMap);
        $data['transport_type'] = !empty($data['transport_id']) ? 2 : 1;
        // 运费模板
        $transport = M('Transport')->where(array('store_id'=>$this->store_id))->select();
        if(C("START_POSITION")){
          $zoneinfo = M('ZonePrice')->where('store_id ='.$this->store_id)->field('id,rate')->select();
          $this->zoneinfo  = json_encode($zoneinfo);
	    }
        $buchongzhiduan=D("Item")->getBuChongZhiDuan($data);
        $brand = M('Brand')->order("sort")->select();
        $this->assign('buchongzhiduan', $buchongzhiduan);
        $this->assign('transport',$transport);
        $this->assign('brand',$brand);
        $this->assign('select_html', $select_html);
        $this->assign('data', $data);
        $this->meta_title = $title;
        $this->display();
    }
    
    
    /**
     * 设置一条或者多条商品的状态
     */
    public function setStatus(){
        $ids = I('request.ids');
        if(empty($ids)){
            $this->error('请选择要操作的商品');
        }
        
        if(!is_array($ids)){
            $ids = (array)$ids;
        }
    
        $Model = 'Item';
        $status = I('request.status');
        // 过滤掉对违规下架、已删除商品的处理
        $uMap['store_id'] = $this->store_id;
        $uMap['status'] = array('in',array(-1,-2));
        $uList = M($Model)->where($uMap)->field('id')->select();
        if(!empty($uList) && $status != -1){ // 违规商品可以删除
            $uIds = array_column($uList,'id');
            $ids = array_diff($ids,$uIds);
        }
        if(empty($ids)){
            $this->error('请勿违规操作');
        }
        $map['id'] = array('in',$ids);
        //店铺上架商品数量
        $item_count = count($ids);
        if ($status == 1) {
            //商品上架前检查 修改后店铺销售区域
            $store_zone = M('ZoneUsed')->where('store_id='.$this->store_id)->getField('areas');
            //店铺独立销售区域
            $store_alone_zone = M('ZonePrice')->where('store_id='.$this->store_id)->getField('areas');
        }
        if ($item_count > 1 && $status == 1) {          
            $alone_arr = $str_arr = array();
            $alone_string = $string = '';
            foreach ($ids as $key => $item_id) {
                //商品销售区域
                $item_zone = M('Item')->where('id='.$item_id)->getField('set_zone');
                //商品的独立销售区域
                $item_alone_zone = M('ItemZone')->alias('IZ')->join('LEFT JOIN __ZONE_PRICE__ ZP ON IZ.zone_id = ZP.id')->where('IZ.item_id='.$item_id)->Field('ZP.areas')->select();
                foreach ($item_alone_zone as $k => $v) {
                    $items_alone_zone .= $v['areas'].',';
                }
                $items_alone_zone_arr = array_filter(explode(',',$items_alone_zone));
                if (!empty($store_alone_zone)) {
                    //存在独立销售区域
                    $intersection_arr = array_intersect($items_alone_zone_arr,explode(',',$store_zone));
                    if ($intersection_arr != $items_alone_zone_arr) {
                       $alone_arr[] = $item_id;
                       unset($ids[$key]);
                    }else{
                        $intersection_arr2 = array_intersect(explode(',',$item_zone),explode(',',$store_zone));
                        if ($intersection_arr2 != explode(',',$item_zone)) {
                            $str_arr[] = $item_id;
                            unset($ids[$key]);
                        }
                    }
                        
                }else{
                    //判断商品销售区域是否在设置的销售区域中
                    $intersection_arr = array_intersect(explode(',',$item_zone),explode(',',$store_zone));
                    if ($intersection_arr != explode(',',$item_zone)) {
                        $str_arr[] = $item_id;
                        unset($ids[$key]);
                    }
                }   
            }
            //独立销售区域
            if (!empty($alone_arr)) {
                $alone_string = implode(',',$alone_arr);
            }
            //销售区域
            if (!empty($str_arr)) {
                $string = implode(',',$str_arr);
            }
        }
        switch ($status){
            case -1 :
                $this->delete($Model, $map, array('success'=>'删除成功','error'=>'删除失败'));
                break;
            case 0  :
                $this->forbid($Model, $map, array('success'=>'下架成功','error'=>'下架失败'));
                break;
            case 1  :
                //商品上架前检查 单个
                if ($item_count == 1) {
                    foreach ($ids as $key => $item_id) {
                        //商品销售区域
                        $item_zone = M('Item')->where('id='.$item_id)->getField('set_zone');
                        //商品的独立销售区域
                        $item_alone_zone = M('ItemZone')->alias('IZ')->join('LEFT JOIN __ZONE_PRICE__ ZP ON IZ.zone_id = ZP.id')->where('IZ.item_id='.$item_id)->Field('ZP.areas')->select();
                        foreach ($item_alone_zone as $k => $v) {
                            $items_alone_zone .= $v['areas'].',';
                        }
                        $items_alone_zone_arr = array_filter(explode(',',$items_alone_zone));
                        if (!empty($store_alone_zone)) {
                            //存在独立销售区域
                            $intersection_arr = array_intersect($items_alone_zone_arr,explode(',',$store_zone));
                            if ($intersection_arr != $items_alone_zone_arr) {
                               $this->error('商品上架失败，此商品独立销售区域超出店铺销售区域！请重新设置销售区域！');
                               break;
                            }else{
                                $intersection_arr2 = array_intersect(explode(',',$item_zone),explode(',',$store_zone));
                                if ($intersection_arr2 != explode(',',$item_zone)) {
                                    $this->error('商品上架失败，此商品销售区域超出店铺销售区域！请重新设置销售区域！');
                                    break;
                                }else{
                                    $this->resume($Model, $map, array('success'=>'上架成功','error'=>'上架失败'));
                                    break;
                                }
                            }          
                        }else{
                            //判断商品销售区域是否在设置的销售区域中
                            $intersection_arr = array_intersect(explode(',',$item_zone),explode(',',$store_zone));
                            if ($intersection_arr != explode(',',$item_zone)) {
                                $this->error('商品上架失败，此商品销售区域超出店铺销售区域！请重新设置销售区域！');
                                break;
                            }else{
                                $this->resume($Model, $map, array('success'=>'上架成功','error'=>'上架失败'));
                                break;
                            }
                        }   
                    }
                }else{
                    //先判断$ids是否为空
                    $maps['id'] = array('in',$ids);
                    $info= '上架成功！';
                    if (isset($alone_string) && ($alone_string != '')) {
                        $info .= '其中独立销售区域超出店铺销售区域的商品ID为：'.$alone_string.'。';
                    }
                    if (isset($string) && ($string != '')) {
                        $info .= '商品销售区域超出店铺销售区域的商品ID为：'.$string.'。';
                    }
                    if (empty($ids)) {
                        $error = str_replace('成功', '失败', $info);
                        $this->error($error);
                        break;
                    }
                    $this->resume($Model, $maps, array('success'=>$info,'error'=>'上架失败'));
                    break;
                }
                //$this->resume($Model, $map, array('success'=>'上架成功','error'=>'上架失败'));
                //break;
            default :
                $this->error('参数错误');
                break;
        }
    }
    
    
    /**
     * 删除商品图片
     * @author ezhu <ezhu@jipukeji.com>
     */
    public function delPic($pid = null, $item_id = null, $thumb = null, $images = null){
    
        $result = array('status'=>1, 'info'=>'图片删除成功！');
    
        // 验证参数的合法性
        if(empty($pid)){
            $result = array('status'=>0, 'info'=>'参数不能为空！');
            $this->ajaxReturn($result, 'JSON');
        }else{
            if(!is_numeric($pid)){
                $result = array('status'=>0, 'info'=>'参数错误！');
                $this->ajaxReturn($result, 'JSON');
            }
        }
    
        // 实例化图片模型
        $picture_model = D('Picture');
    
        // 获取商品图片缩略图规格配置
        $thumb_size = C('UPLOAD_PIC_THUMB_SIZE.ITEM_PIC');
    
        if($picture_model->delById($pid, $thumb_size)){
            if($item_id && is_numeric($item_id)){
                // 更新商品图片数据
                $data['id'] = $item_id;
                $data['thumb'] = $thumb;
                $data['images'] = $images;
                if(M('Item')->save($data)){
                    $this->ajaxReturn($result, 'JSON');
                }else{
                    $result = array('status'=>0, 'info'=>'图片删除失败！');
                    $this->ajaxReturn($result, 'JSON');
                }
            }
        }else{
            $result = array('status'=>0, 'info'=>'图片删除失败！');
            $this->ajaxReturn($result, 'JSON');
        }
    
        $this->ajaxReturn($result, 'JSON');
    }
    
    /**
     * 批量生成二维码
     * @author ezhu <ezhu@jipukeji.com>
     */
    public function createQrcode(){
        $where['status'] = 1;
        $items = M('Item')->where($where)->getField('id', true);
    
        if($items && is_array($items)){
            foreach($items as $item){
                get_qrcode($item, 0, 2.6, 1);
            }
        }
        //记录行为
        action_log('create_item_qrcode', 'item', 'all', UID);
        $this->meta_title = '二维码批量生成';
        $this->display('qrcode');
    }
    
    
    /**
     * 手机端-商品详情，可编辑商品价格
     */
    public function detail(){
        $id = I('get.id');
        //验证参数的合法性
        if(!(is_numeric($id) && $id > 0)){
            $this->error('参数非法！');
        }
        $uid = $_SESSION['jipushop_home']['user_auth']['uid']?$_SESSION['jipushop_home']['user_auth']['uid']:0;
        $user = D('Addons://StoreSel/StoreSel')->where(array('member_id' => $uid))->find();
        //实例化数据模型
        $item_model = D('Item');
        //获取商品数据
        $data = $item_model->itemInfo($id);
        
        if(empty($data)){
            $this->error('商品不存在！', U('Item/index'));
        }elseif($data['status'] < 0){
            $this->error('该商品已违规下架！', U('Item/index'));
        }
        
        $this->assign('data',$data);
        $this->display();
    }
    
    
    /**
     * 手机端-设置产品价格和库存
     */
    public function setItem(){
        $price = I('price',0,'floatval');
        $stock = I('stock',0,'intval');
        $id = I('id',0,'intval');
        if($price < 0 || $stock < 0 ){
            $this->error('价格和库存不能小于0');
        }
        if(!$id){
            $this->error('参数错误');
        }
        
        $model = M('Item');
        $map['id'] = $id;
        $map['store_id'] = $this->store_id;
        $map['status'] = array('egt',0);
        
        $data['price'] = $price;
        $data['stock'] = $stock;
        $rst = $model->where($map)->save($data);
        $rst !== false ? $this->success('操作成功！') : $this->error('操作失败！');
        exit;
    }
    
    
    /**
     * 手机端-批量设置产品价格和库存
     */
    public function setItemSpec(){
        $price = I('price',0,'floatval');
        $stock = I('stock',0,'intval');
        $id = I('id',0,'intval');
        if($price < 0 || $stock < 0 ){
            $this->error('参数不能小于0');
        }
        if(!$id){
            $this->error('参数错误');
        }
        
        $model = M('ItemSpecifiction');
        
        $iteMap['id'] = $id;
        $iteMap['store_id'] = $this->store_id;
        $iteMap['status'] = array('egt',0);
        $isExist = M('Item')->where($iteMap)->find();
        if(!$isExist){
            $this->error('商品不存在！');
        }
        
        $map['item_id'] = $id;
        
        $data['price'] = $price;
        $data['quantity'] = $stock;
        $rst = $model->where($map)->save($data);
        $rst !== false ? $this->success('操作成功！') : $this->error('操作失败！');
        exit;
    }
    
    
    /**
     * ajax 获取品牌
     */
    public function getBrand(){
        $cid_1 = I('get.cid_1',0,'intval');
        $cid_2 = I('get.cid_2',0,'intval');
        $cid_3 = I('get.cid_3',0,'intval');
        $brand_id = I('get.brand_id',0,'intval');
        $cid = 0;
        if(!empty($cid_1)){
            $cid = $cid_1;
        }
        
        if(!empty($cid_2)){
            $cid = $cid_2;
        }
        
        if(!empty($cid_3)){
            $cid = $cid_3;
        }
        
        $brand = array();
        if(!empty($cid)){
            $map['status'] = 1;
            $map['cid'] = $cid;
            $order = '`recommend` DESC,`sort` DESC';
            $brand = M('Brand')->where($map)->order($order)->select();
        }
        $this->assign('brand_id',$brand_id);
        $this->assign('brand',$brand);
        $this->display();
        
    }
    
}

  

  